//将ID、ParentID这种数据格式转换为树格式 
var arrayToTree = function (data, id, pid)     
{
    if (!data || !data.length) return [];
    var targetData = [];//存储数据的容器(返回) 
    var records = {};
    var itemLength = data.length; //数据集合的个数
    for (var i = 0; i < itemLength; i++)
    {
        var o = data[i];
        records[o[id]] = o;
    }
    for (var i = 0; i < itemLength; i++)
    {
        var currentData = data[i];
        var parentData = records[currentData[pid]];
        if (!parentData)
        {
            targetData.push(currentData);
            continue;
        }
        parentData.children = parentData.children || [];
        parentData.children.push(currentData);
    }
    return targetData;
}
	
function dropPrev(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
function dropInner(treeId, nodes, targetNode) {
	if (targetNode && targetNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			if (!targetNode && curDragNodes[i].dropRoot === false) {
				return false;
			} else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
function dropNext(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}

var log, className = "dark", curDragNodes, autoExpandNode;
function beforeDrag(treeId, treeNodes) {
	for (var i=0,l=treeNodes.length; i<l; i++) {
		if (treeNodes[i].drag === false) {
			curDragNodes = null;
			return false;
		} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
			curDragNodes = null;
			return false;
		}
	}
	curDragNodes = treeNodes;
	return true;
}
function beforeDragOpen(treeId, treeNode) {
	autoExpandNode = treeNode;
	return true;
}

function fontCss(treeNode) {
	var aObj = $("#" + treeNode.tId + "_a");
aObj.removeClass("copy").removeClass("cut");
if (treeNode === curSrcNode) {
	if (curType == "copy") {
			aObj.addClass(curType);
		} else {
			aObj.addClass(curType);
		}			
	}
}

//以下方法 为复制粘贴方法
function beforeClick(treeId, treeNode) {
	return !treeNode.isCur;
}

var curSrcNode, curType;
function setCurSrcNode(treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	if (curSrcNode) {
		delete curSrcNode.isCur;
		var tmpNode = curSrcNode;
		curSrcNode = null;
		fontCss(tmpNode);
	}
	curSrcNode = treeNode;
	if (!treeNode) return;

	curSrcNode.isCur = true;			
	zTree.cancelSelectedNode();
	fontCss(curSrcNode);
}
function copy(e) {
	hideRMenu();
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
nodes = zTree.getSelectedNodes();
if (nodes.length == 0) {
	alert("请先选择一个节点");
	return;
}
curType = "copy";
	setCurSrcNode(nodes[0]);
}
function cut(e) {
	hideRMenu();
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
nodes = zTree.getSelectedNodes();
if (nodes.length == 0) {
	alert("请先选择一个节点");
	return;
}
curType = "cut";
	setCurSrcNode(nodes[0]);
}
function paste(e) {
	hideRMenu();
	if (!curSrcNode) {
		alert("请先选择一个节点进行 复制 / 剪切");
	return;
}
var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
nodes = zTree.getSelectedNodes(),
targetNode = nodes.length>0? nodes[0]:null;
if (curSrcNode === targetNode) {
	alert("不能移动，源节点 与 目标节点相同");
	return;
} else if (curType === "cut" && ((!!targetNode && curSrcNode.parentTId === targetNode.tId) || (!targetNode && !curSrcNode.parentTId))) {
	alert("不能移动，源节点 已经存在于 目标节点中");
	return;
} else if (curType === "copy") {
	targetNode = zTree.copyNode(targetNode, curSrcNode, "inner");
} else if (curType === "cut") {
	targetNode = zTree.moveNode(targetNode, curSrcNode, "inner");
	if (!targetNode) {
		alert("剪切失败，源节点是目标节点的父节点");
		}
		targetNode = curSrcNode;
	}
	setCurSrcNode();
	delete targetNode.isCur;
	zTree.selectNode(targetNode);
}

//更新拖拽后的id和pid
var updateTrees = function(nodes, pid, cNodes){
	if(!cNodes) cNodes = [];
	for(var o in nodes){
		var node = nodes[o];
		node.pid=pid;
		node.id=(parseInt(o)+1);
		cNodes.push(node);
		if(node.children){
			updateTree(node.children, node.id);
		}
	}
	
	function updateTree(nodes, pid){
		for(var o in nodes){
			var node = nodes[o];
			node.pid=pid;
			node.id=pid+"-"+(parseInt(o)+1);
			if(node.children){
				updateTree(node.children, node.id);
			}
		}
	}
}

//右键菜单
function OnRightClick(event, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
	zTree.cancelSelectedNode();
	showRMenu("root", event.screenX-420, event.screenY-160);
} else if (treeNode && !treeNode.noR) {
	zTree.selectNode(treeNode);
	showRMenu("node", event.screenX-420, event.screenY-160);
	}
}

function showRMenu(type, x, y) {
	var rMenu = $("#rMenu");
$("#rMenu ul").show();
if (type=="root") {
	$("#m_del").hide();
	$("#m_check").hide();
	$("#m_unCheck").hide();
} else {
	$("#m_del").show();
	$("#m_check").show();
	$("#m_unCheck").show();
}
rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

$("body").bind("mousedown", onBodyMouseDown);
}
function hideRMenu() {
	var rMenu = $("#rMenu");
if (rMenu) rMenu.css({"visibility": "hidden"});
$("body").unbind("mousedown", onBodyMouseDown);
}
function onBodyMouseDown(event){
	var rMenu = $("#rMenu");
if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
	rMenu.css({"visibility" : "hidden"});
	}
}

//删除节点
function removeTreeNode() {
	hideRMenu();
	var roleCode = $("#treeDemo").attr("role");
	var question = "即将执行删除操作，\n\n请确认";
	if(!roleCode==""){
		var question = "即将执行删除操作，删除后，该指标所有应用配置将消失\n\n请确认";
	}
	if (confirm(question)==true){
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		var nodes = zTree.getSelectedNodes();
		if (nodes && nodes.length>0) {
			if (nodes[0].children && nodes[0].children.length > 0) {
				var msg = "只能删除该节点下的叶子节点。\n\n请确认！";
					if (confirm(msg)==true){
						if(!roleCode==""){
							deleteNodes(nodes[0]);
						}
						zTree.removeNode(nodes[0]);
					}
			} else {
				if(!roleCode==""){
					deleteNodes(nodes[0]);
				}
				zTree.removeNode(nodes[0]);
			}
		}
	}
	
	function deleteNodes(nodes){
		if(nodes.children && nodes.children.length > 0){
			var quotaCode = nodes.code;
			var pid=nodes.pid;
		    var id=nodes.id;
			deletePost(quotaCode, roleCode, pid,id,function(data){
				if(!data.success){
					drgUI.error(data.errorMessage);
					return false;
				}
			});
			for(var o in nodes.children){
				var node = nodes.children[o];
				deleteNodes(node);
			}
		}else{
			var quotaCode = nodes.code;
			var pid=nodes.pid;
		    var id=nodes.id;
			deletePost(quotaCode, roleCode,pid,id, function(data){
				if(!data.success){
					drgUI.error(data.errorMessage);
					return false;
				}
			});
		}
	}
	
	function deletePost(quotaCode, roleCode,pid,id, callback){
		if(id && id.split('-').length==3){
			$.post(contextPath + "/quota/deleteQuotaSettingByCode.dhc", {quotaCode: quotaCode, roleCode: roleCode,pid:pid,id:id}).done(function(data){
				callback(data);
			})
		}
	}
}

//添加节点
function add() {
	hideRMenu();
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	var newNode = { name:""};
	if (zTree.getSelectedNodes()[0]) {
		newNode.checked = false;//zTree.getSelectedNodes()[0].checked;
		newNode = zTree.addNodes(zTree.getSelectedNodes()[0], newNode);
	} else {
		newNode = zTree.addNodes(null, newNode);
	}
	if(newNode.length>0)
	$("#"+newNode[0].tId).append("<input id='newNodeId' /><button style=' background-color: rgba(121, 218, 89, 0.78); font-size: 15px;width: 20px;'>√</button>");
	//取指标为1和2的
	$.post(contextPath + "/quota/getQuotaRoleList.dhc").done(function(data_1){
		   var quotas = data_1.data;
			//添加按钮实现
			$CommonUI.combobox($("#"+newNode[0].tId).find("input"),quotas,"QUOTADESC","QUOTACODE");			
			$("#"+newNode[0].tId).find("button").click(function(){
				var zTreeSimp = zTree.transformToArray(zTree.getNodes());
			  for(var o in zTreeSimp){
					var node = zTreeSimp[o];
					if(node.code==$("#"+newNode[0].tId).find("input").combobox("getValue")){
						alert("该指标已存在");
						return;
					}
				}
				newNode[0].code=$("#"+newNode[0].tId).find("input").combobox("getValue");
				newNode[0].name=$("#"+newNode[0].tId).find("input").combobox('getText');
				zTree.updateNode(newNode[0]);
				$("#"+newNode[0].tId).find(".combo").remove();
				$("#"+newNode[0].tId).find("button").remove();
			})
	});
}
